/*
 * Dual Select JQuery Widget
 *
 * @author Giancarlo Bellido
 */

jQuery.widget("ui.dualselect", {

	container: null,

	components: {
		left: {
			container: null,
			list: null,
			toolbar: null
		},
		right: {
			container: null,
			list: null,
			toolbar: null
		}
	},

	_init: function()
	{
		var _calculateHeight = function(obj, ll) {
			var size = $(obj).attr("size");
			return (size) ? size * 25 : 125;
		};

		this.container = this.element.wrap('<div class="dual-select"></div>').parent();
		this.container.data("dualselect", this.element.data("dualselect"));

		var e = this.element;

		var self = this;

		var lc = this.components.left.container = document.createElement("DIV");
		var rc = this.components.right.container = document.createElement("DIV");
		
		var ll = this.components.left.list  = document.createElement("UL");
		var rl = this.components.right.list = document.createElement("UL");

		var lt = this.components.left.toolbar = document.createElement("DIV");
		var rt = this.components.right.toolbar = document.createElement("DIV");


		e.children().each(function() {
			var li = document.createElement("LI");

			$(li).attr("class", $(this).attr("class")).html(this.innerHTML).click(function() { $(this).toggleClass('selected') });
			li.tag = $(this).val();
			$(ll).append(li);
		});

		this.container.append(lc).append(rc);

		$(lc).append(ll).append(lt);
		$(rc).append(rl).append(rt);

		$(rl).height( $(ll).height(_calculateHeight(e)).height() );

		$(lt).html(
			'<button type="button" class="search">Search</button>' +
			'<button type="button" class="add">Add</button>'
		).addClass("toolbar").children(".add").click(function() { self.add(); });

		$(rt).html(
			'<button type="button" class="search">Search</button>' +
			'<button type="button" class="remove">Remove</button>'
		).addClass("toolbar").children(".remove").click(function() { self.remove(); });

		e.remove();


		$(this.container).attr("id", e.attr("id"));

	},

	/* METHODS */
	add: function() {
		$(this.components.left.list).children('.selected').removeClass('selected').appendTo($(this.components.right.list));
	},

	remove: function() {
		$(this.components.right.list).children('.selected').removeClass('selected').appendTo($(this.components.left.list));
	},

	selected: function() {
		return $(this.components.right.list).children();
	},

	/* Returns Array containing values of selected items */
	values: function() {
		var v = [];
		this.selected().each(function() {
			v.push(this.tag);
		});

		return v;
	},

	/* Returns array containing the text of the selected items */
	selectedText: function() {
		var v = [];
		this.selected().each(function() { v.push($(this).text()); });
		return v;
	},

	/* Returns array containing the html of the selected items */
	selectedHtml: function() {
		var v = [];
		this.selected().each(function() { v.push($(this).html()); });
		return v;
	},



});

jQuery.ui.dualselect.getter = [ "selected", "values", "selectedText", "selectedHtml" ];
